﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Runtime.InteropServices;
using System.Windows;
using WebCam.Logic.Detectors;
using System.Windows.Input;
using System.Diagnostics;
using WebcamCore;
using System.Windows.Forms;

namespace WebCamWorker.ViewModel
{
    public class VMWebCamShow : INotifyPropertyChanged
    {
        CoreController controller;
        public VMWebCamShow()
        {
            //AddPointCommand = new RelayCommand((object param) => ExecutedAddPointCommand(param), (object param) => CanExecuteAddPointCommand(param));
            //FinishInitCommand = new RelayCommand((object param) => { controller.InitCompleted(); }, (object param) => { return true; });
        }

        //public static ICommand AddPointCommand;
        //public static ICommand FinishInitCommand;
        
        //private bool CanExecuteAddPointCommand(object param)
        //{
        //    return true;
        //}

        //private void ExecutedAddPointCommand(object param)
        //{
        //    //FingerTypes name = (FingerTypes)Enum.Parse(typeof(FingerTypes), param.ToString());
        //    //controller.AddControlPoint(name);
        //    //int x = 2 + (int)param;
        //}

        public void Start()
        {
            controller = new CoreController();
            controller.OnOutputImageFormed += new OutputImageFormed(controller_OnOutputImageFormed);
            controller.OnWindowStartCommand += new WindowStart(controller_OnWindowStartCommand);

            controller.Start();
        }

        void controller_OnMotionCaptureImageFormed(Bitmap outputImage, double leftAngle, double rightAngle)
        {
            //MotionCaptureImageFormed
        }
        MotionCaptureWindow wnd = null;
        JediWindow jwnd = null;
        void controller_OnWindowStartCommand(string programName)
        {
            switch(programName)
            {
                case "Butterfly":
                    wnd = new MotionCaptureWindow();
                    var screens = Screen.AllScreens;
                    Screen secondaryScreen = Screen.AllScreens.FirstOrDefault(p => p.Primary == false);
                    if (secondaryScreen == null)
                    {
                        throw new Exception("Некорректное число экранов");
                    }
                    wnd.Left = secondaryScreen.WorkingArea.X;
                    wnd.Top = secondaryScreen.WorkingArea.Y;
                    wnd.Width = secondaryScreen.WorkingArea.Width;
                    wnd.Height = secondaryScreen.WorkingArea.Height;
                    wnd.Topmost = true;
                    controller.OnMotionCaptureImageFormed += new MotionCaptureImageFormed(wnd.ViewModel.MotionCaptureImageFormed);
                    wnd.Show();                    
                    break;
                case "KillButterfly":
                    if (wnd != null)
                    {
                        controller.OnMotionCaptureImageFormed -= new MotionCaptureImageFormed(wnd.ViewModel.MotionCaptureImageFormed);
                        wnd.Close();
                        wnd = null;
                    }
                    break;
                case "Lightsaber":
                    jwnd = new JediWindow();
                    screens = Screen.AllScreens;
                    secondaryScreen = Screen.AllScreens.FirstOrDefault(p => p.Primary == false);
                    if (secondaryScreen == null)
                    {
                        throw new Exception("Некорректное число экранов");
                    }
                    jwnd.Left = secondaryScreen.WorkingArea.X;
                    jwnd.Top = secondaryScreen.WorkingArea.Y;
                    jwnd.Width = secondaryScreen.WorkingArea.Width;
                    jwnd.Height = secondaryScreen.WorkingArea.Height;
                    jwnd.Topmost = true;
                    controller.OnJedyImageFormed += new JediImageFormed(jwnd.ViewModel.JediImageFormed);
                    jwnd.Show();
                    break;
                case "KillLightsaber":
                    if (jwnd != null)
                    {
                        controller.OnJedyImageFormed -= new JediImageFormed(jwnd.ViewModel.JediImageFormed);
                        jwnd.Close();
                        jwnd = null;
                    }
                    break;
            }
        }

        void controller_OnColorChanged(System.Drawing.Color color)
        {
            //Colors = controller.ControlPoints.Select(p => p.Color).ToList();
        }

        List<int> combo = new List<int>();
        public List<int> Combo 
        { 
            get 
            { 
                return combo; 
            } 
            set 
            { 
                combo = value; 
                OnPropertyChanged("Combo"); 
            } 
        }

        void controller_OnOutputImageFormed(Bitmap outputImage, List<int> combo)
        {
            Image = loadBitmap(outputImage);
            if (combo.Count != 0)
            {
                //combo.Add(1);
            }
            Combo = combo;
            //Colors = controller.ControlPoints.Select(p => p.PointColor).ToList();
        }

        private List<System.Drawing.Color> colors;
        public List<System.Drawing.Color> Colors
        {
            get { return colors; }
            set
            {
                colors = value;
                OnPropertyChanged("Colors");
            }
        }

        [DllImport("gdi32")]
        static extern int DeleteObject(IntPtr o);

        private static BitmapSource loadBitmap(System.Drawing.Bitmap source)
        {
            IntPtr ip = source.GetHbitmap();
            BitmapSource bs = null;
            try
            {
                bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip,
                   IntPtr.Zero, Int32Rect.Empty,
                   System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
            }
            finally
            {
                DeleteObject(ip);
            }

            return bs;
        }

        public int Width { get { return controller.Width; } }
        public int Height { get { return controller.Height; } }

        private ImageSource source;
        public ImageSource Image
        {
            get { return source; }
            private set { source = value; OnPropertyChanged("Image"); }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        internal void Close()
        {
            if(controller != null)
                controller.Stop();
        }
    }
}
